#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2018/1/10 0010 19:06
# @Author  : Arliki
# @File    : auto_jump.py
import os
import sys
import re
import json
import time
import random
import subprocess
from PIL import Image


def __get_pho_size():
    pho_size = os.popen('adb shell wm size').read()
    # print(pho_size)
    if not pho_size:
        print("请安装ADB驱动或检查配置环境")
        sys.exit()
    m = re.search(r'(\d+)x(\d+)', pho_size)
    if m:
        return "%s_%s" % (m.group(1), m.group(2))
    else:
        exit('获取不到分辨率')


def init():
    # 初始化函数，读取配置 1920_1080
    pho_size = __get_pho_size()
    config_path = 'config/%s/config.json' % pho_size
    print(pho_size)
    if os.path.exists(config_path):
        with open(config_path, 'r') as f:
            print("config path:", config_path)
            return json.loads(f.read())
    else:  # 默认
        with open('config/default.json', 'r') as f:
            print("default")
            return json.loads(f.read())


def get_screen_img():
    process = subprocess.Popen('adb shell screencap -p', shell=True, stdout=subprocess.PIPE)
    screenshot = process.stdout.read()
    bytes_screenshot = screenshot.replace(b'\r\r\n', b'\n')
    with open('auto_jump.png', 'wb') as f:
        f.write(bytes_screenshot)


def find_piece(img, config):
    # 分析棋子
    w, h = img.size
    # 图像的像素矩阵
    img_pixel = img.load()
    start_y = 0
    # 棋子边界
    side_x = w // 8
    piece_y_max = 0
    # 检测图片取中间1/3 50px为误差
    for i in range(h // 3, h * 2 // 3, 50):
        first_pixel = img_pixel[0, i]
        for j in range(1, w):
            # 非纯
            pixel = img_pixel[j, i]
            if pixel[:-1] != first_pixel[:-1]:
                start_y = i - 50
        if start_y:
            break
    # 从上往下扫描棋子
    left = 0
    right = 0
    for i in range(start_y, h * 2 // 3):
        flag = True
        for j in range(side_x, w - side_x):
            pixel = img_pixel[j, i]
            if (50 < pixel[0] < 60) and (53 < pixel[1] < 63) and (95 < pixel[2] < 110):
                if flag:
                    left = j
                    flag = False
                right = j
                piece_y_max = max(i, piece_y_max)
    piece_x = (left + right) // 2
    piece_y = piece_y_max - config["piece_base_height_1_2"]
    print(piece_x, piece_y)
    exit()


def auto_jump(distance, param):
    pass


def run():
    config = init()
    while True:
        get_screen_img()  # 获取截图
        img = Image.open('auto_jump.png')
        sta_x, star_y, end_x, end_y = find_piece(img, config)
        distance = ((end_y - star_y) ** 2 + (end_x - sta_x) ** 2) ** 0.5
        auto_jump(distance, config('jump_ratio'))
        time.sleep(random.randint(1, 2))


if __name__ == '__main__':
    run()
